package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;
    public PageResult<Brand> queryBrandsByPage(String key, Integer page, Integer rows,String sortBy,Boolean desc){
        //进行多条件查询
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        // 判断一下key是否为空，使用StringUtils工具类
        System.out.println("key--------------"+key);
        if(StringUtils.isNotBlank(key)){
            //进行模糊查询
            queryWrapper.like("name",key).or().eq("letter",key);
        }
        PageHelper.startPage(page,rows);
        if(StringUtils.isNotBlank(sortBy)){
            queryWrapper.orderBy(true,!desc,sortBy);
        }
        List<Brand> brands = brandMapper.selectList(queryWrapper);
        // 包装成pageInfo
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        // 包装成分页结果集返回
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }
    @Transactional
    public void insertBrand(Brand brand, List<Long> cids) {
        this.brandMapper.insert(brand);
        // 在新增中间表
        cids.forEach(cid -> {
            this.brandMapper.insertCategoryAndBrand(cid,brand.getId());
        });
    }
    @Transactional
    public void updateBrand(Brand brand, List<Long> cids) {
        //先删除中间表
        brandMapper.deleteCategoryAndBrand(brand.getId());
        brandMapper.updateById(brand);
        // 在新增中间表
        cids.forEach(cid -> {
            this.brandMapper.insertCategoryAndBrand(cid,brand.getId());
        });
    }
    @Transactional
    public void deleteBrand(Long bid){
        //先删除品牌表
        brandMapper.deleteById(bid);
        //再删除中间表
        brandMapper.deleteCategoryAndBrand(bid);
    }
    public List<Brand> getBrandsList(Long cid){
        List<Brand> brands = brandMapper.selectByCid(cid);
        return brands;
    }
}
